package com.jing.serial.demos.web;

import com.jing.serial.config.TaskConfig;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class MyWebSocketHandler extends TextWebSocketHandler {


    TaskConfig taskConfig;

    public MyWebSocketHandler(TaskConfig taskConfig){
        this.taskConfig=taskConfig;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("连接: " + session.getId());
        taskConfig.addSession(session); // 添加会话到集合
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("收到: " + message.getPayload());
        // Echo the received message back to the client
        session.sendMessage(new TextMessage("Echo: " + message.getPayload()));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("断开: " + session.getId());
        taskConfig.removeSession(session); // 从集合中移除会话
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("错误: " + exception.getMessage());
    }


}
